package com.itheima.sh.web;

import com.itheima.sh.pojo.User;
import com.itheima.sh.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集，获取前端参数
        //request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        //创建用户对象，存储前端数据
        User user = new User(username, password);
        //获取session中的验证码
        HttpSession session = request.getSession();
        String checkCode = (String) session.getAttribute("checkCode");
        //如果验证码正确
        if (checkCode.equalsIgnoreCase(code)){
            //创建Service对象调用对应方法
            UserServiceImpl userService = new UserServiceImpl();
            boolean register = userService.register(user);
            //返回true可以注册
            if (register){
                response.getWriter().print(true);
            }else {
                response.getWriter().print(false);
            }
        } else {
            //如果验证码错误
            response.getWriter().print(false);
        }

    }
}